<template>
    <div>
         <div class="headstyle">
            <el-row :gutter="20">
                <el-col :span="16">
                    <div class="grid-content bg-purple">
                    <span class="locsty"><i class="el-icon-location iconsty"></i>当前位置：<router-link to="/coursemanage">课程管理</router-link>><router-link to="/coursemanage/editcourse">课程编辑</router-link>>章节编辑</span>
                    </div>
                </el-col>        
                <el-col :span="8" class="loc-index">
                    <div class="grid-content bg-purple">
                        <el-button type="primary" @click="resetForm()" class="backbtn">新增章节</el-button>
                        <el-button type="primary" plain @click="goTo('/coursemanage')" class="backbtn">返回列表</el-button>                   
                    </div>
                </el-col>
            </el-row>
        </div>
        <div class="contentstyle">
            <div class="contentleft">
               <el-table
                    :data="tableData.filter(data => tableData[0].chptid!='')"
                    style="width: 100%">
                    <el-table-column  prop="chptname" label="章节名称" show-overflow-tooltip align="center"> </el-table-column>
                    <el-table-column  prop="chpttype" label="课件类型" show-overflow-tooltip align="center"> </el-table-column>
                    <el-table-column align="center" width="200">    
                    <template slot-scope="scope">
                        <el-button
                        size="mini"
                        @click="handleEdit(scope.$index, scope.row)">Edit</el-button>
                        <el-button
                        size="mini"
                        type="danger"
                        @click="handleDelete(scope.$index, scope.row)">Delete</el-button>
                    </template>
                    </el-table-column>
                </el-table>
            </div>
            <div class="contentright">
               <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
                <el-form-item label="章节名称" prop="chaptername">
                  <el-input v-model="ruleForm.chaptername"></el-input>
                </el-form-item>
                <el-form-item label="课件类型" prop="chaptertype">
                  <el-select v-model="ruleForm.chaptertype" placeholder="请选择课件类型" class="selsty">
                    <el-option label="视频" value="视频"></el-option>
                    <el-option label="pdf" value="pdf"></el-option>
                    <el-option label="图片" value="图片"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="课件展示" prop="chapterfileshow">
                     <el-link  :class="coursewarey" :href="courseurl" target="view_window">查看课件<i class="el-icon-view el-icon--right"></i> </el-link>
                     <span :class="coursewaren">请上传</span>
                </el-form-item>
                <el-form-item label="课件材料" prop="chapterinfo">
                  <el-upload
                      class="upload-demo"
                      ref="upload"
                      action="/Course"                    
                      :limit="1"
                      :on-progress="uploadVideoProcess"
                      :on-remove="handleRemove"
                      :on-success="handleVideoSuccess"
                      :before-upload="beforeUploadVideo"
                      :auto-upload="false"
                      accept=".jpg,.jpeg,.png,.mp4,.pdf,.avi"
                      :http-request="uploadSectionFile">
                    <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
                    <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload" >上传到服务器</el-button>
                    <div class="el-upload__tip" slot="tip">视频大小不能超过500M;&nbsp;&nbsp;文档只能上传pdf类;&nbsp;&nbsp;图片只能上传jpg/png格式<br>
                     一个章节只能有一个课件材料，二次上传默认覆盖上一个课件材料
                    </div>
                  </el-upload>
                </el-form-item>                                                                                   
                <el-form-item>
                  <el-button type="primary btnsty" @click="submitForm('ruleForm')">保存</el-button>                                
                </el-form-item>
              </el-form> 
            </div>
        </div>
    </div>
</template>
<script>
export default {
  data() {
    return {
      coursewarey: "see",
      coursewaren: "",
      courseurl: "",
      couid: this.$route.params.couid,
      editid: "",
      tableData: [
        {
          chptname: "",
          chptid: "",
          cosid: "",
          chpttype: ""
        }
      ],
      search: "",
      ruleForm: {
        chaptername: "",
        chaptertype: "",
        chapterinfo: "",
        chapterurl: "",
        chapterfileshow:""
      },
      rules: {
        chaptername: [
          { required: true, message: "请输入章节名称", trigger: "blur" }
        ],
        chaptertype: [
          { required: true, message: "请选择课件类型", trigger: "change" }
        ]
      }
    };
  },
  mounted: function() {
    this.selectchpater();
  },
  methods: {
    selectchpater() {
      if (this.couid != undefined) {
        //加载左侧章节列表
        this.$axios
          .get("/Course/" + this.couid + "/V11")
          .then(json => {
            var chaptList = json.data;
            var chaptlistdata = [];
            for (let i = 0; i < chaptList.length; i++) {
              var item = {
                chptid: chaptList[i].Cw_Id,
                chptname: chaptList[i].Cw_Name,
                cosid: chaptList[i].Cos_ID,
                chpttype: chaptList[i].Cw_type
              };
              chaptlistdata[i] = item;
            }
            this.tableData = chaptlistdata;
          })
          .catch(error => {});
      } else {
        this.$message({
          message: "课程信息获取失败！",
          type: "info"
        });
        this.$router.push("/coursemanage");

      }
    },
    beforeUploadVideo: function(file) {},
    uploadVideoProcess: function(event, file, fileList) {},
    handleRemove(file, fileList) {
      //console.log(file, fileList);
    },
    handleVideoSuccess(response, file, fileList) {
      //console.log(response);
      //console.log(file);
      //console.log(fileList);
    },
    handleEdit(index, row) {
      var id = row.chptid;
      this.$confirm(
        "切换章节之前，请保存当前章节的内容编辑，是否继续切换?",
        "提示"
      ).then(() => {
        this.$axios
          .get("/Course/" + id + "/V12")
          .then(json => {
            this.coursewarey = "";
            this.coursewaren = "see";
            this.courseurl = this.$store.state.respath + json.data.Cw_Url;
            this.editid = json.data.Cw_Id;
            this.ruleForm.chaptername = json.data.Cw_Name;
            this.ruleForm.chaptertype = json.data.Cw_type;
            this.ruleForm.chapterurl = json.data.Cw_Url;
            this.$refs.upload.clearFiles();
          })
          .catch(error => {});
      });
    },
    handleDelete(index, row) {
      var id = row.chptid;
      this.$confirm("确定要删除选中的文件吗?", "提示").then(() => {
        this.$axios
          .delete("/Course/" + id + "/V15")
          .then(json => {
            if (json.data == 1) {
              this.$message({
                message: "删除成功！",
                type: "success"
              });
              this.selectchpater();
            }
          })
          .catch(error => {});
      });
    },
    goTo(path) {
      this.$router.replace(path);
    },

    //上传材料
    submitUpload() {
      let list = document.getElementsByClassName(
        "el-upload-list__item is-ready"
      );
      if (list.length == 0) {
        this.$message({
          type: "warning",
          message: "请选择需要上传的文件"
        });
        return;
      }
      this.$refs.upload.submit();
    },

    uploadSectionFile(param) {
      const loading = this.$loading({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      var fileObj = param.file;
      // FormData 对象
      var form = new FormData();
      // 文件对象
      form.append("file", fileObj);
      form.append("chaptertype", this.ruleForm.chaptertype);
      var chaptertype = this.ruleForm.chaptertype;
      if(chaptertype==""){
        chaptertype="-1";
      }
      this.$axios
        .post("/Course/" + chaptertype + "/V16", form, {
          headers: {
            "Content-Type": "application/octet-stream",
            "Access-Control-Allow-Origin": "*"
          }
        })
        .then(json => {
          if (json.data.flag == true) {
            this.ruleForm.chapterurl = json.data.chpturl;
            this.ruleForm.chaptertype = json.data.type;
            this.$message({
              type: "success",
              message: json.data.Msg
            });
            this.coursewarey = "";
            this.coursewaren = "see";
            this.courseurl =
              this.$store.state.respath + this.ruleForm.chapterurl;
            this.$refs.upload.clearFiles();
          } else if (json.data.flag == false) {
            this.$message({
              type: "error",
              message: json.data.Msg
            });
          }
          loading.close();
        })
        .catch(error => {});
    },
    //新增章节
    resetForm() {
      this.$confirm(
        "切换章节之前，请保存当前章节的内容编辑，是否继续切换?",
        "提示"
      ).then(() => {
        this.coursewarey = "see";
        this.coursewaren = "";
        this.courseurl = "";
        this.editid = "";
        this.ruleForm.chaptername = "";
        this.ruleForm.chapterurl = "";
        this.ruleForm.chaptertype = " ";
        this.ruleForm.chapterinfo = "";
        this.$refs.upload.clearFiles();
      });
    },
    //保存
    submitForm(formName) {
      if (this.editid != "") {
        this.$refs[formName].validate(valid => {
          if (valid) {
            var list = {
              Cw_Name: this.ruleForm.chaptername,
              Cw_Url: this.ruleForm.chapterurl,
              Cw_type: this.ruleForm.chaptertype,
              Cos_ID: this.couid
            };
            this.$axios
              .put("/Course/" + this.editid + "/V14", list)
              .then(Jsondata => {
                if (Jsondata.data) {
                  this.$message({
                    type: "success",
                    message: "保存成功！"
                  });
                  this.selectchpater();
                } else {
                  this.$message({
                    type: "error",
                    message: "保存失败，请重试或检查登录状态！"
                  });
                }
              })
              .catch(error => {});
          } else {
            //console.log("error submit!!");
            return false;
          }
        });
      } else {
        this.$refs[formName].validate(valid => {
          if (valid) {
            if (this.ruleForm.chapterurl == "") {
              this.$message({
                type: "info",
                message: "选取的文件还未上传，请上传之后再保存!"
              });
              return false;
            }
            var list = {
              Cw_Name: this.ruleForm.chaptername,
              Cw_Url: this.ruleForm.chapterurl,
              Cw_type: this.ruleForm.chaptertype,
              Cos_ID: this.couid
            };
            this.$axios
              .post("/Course/V13", list)
              .then(Jsondata => {
                if (Jsondata.data != 0) {
                  this.$message({
                    type: "success",
                    message: "保存成功！"
                  });
                  this.editid = Jsondata.data;
                  this.selectchpater();
                } else {
                  this.$message({
                    type: "error",
                    message: "保存失败，请重试或检查登录状态！"
                  });
                }
              })
              .catch(error => {});
          } else {
            console.log("error submit!!");
            return false;
          }
        });
      }
    }
  }
};
</script>

<style scoped>
/*.loc-index {
  padding-left: 150px !important;
}*/
.see {
  display: none;
}

.backbtn {
  width: 100px;
}
.headstyle {
  border-bottom: 2px solid #e5e5e5;
  padding-bottom: 20px;
}
.locsty {
  font-size: 16px;
  font-family: "Microsoft YaHei";
}
.iconsty {
  color: #53b9fe;
  font-size: 22px;
}
a {
  text-decoration: none;
  color: black;
}
.contentstyle {
  width: 75%;
  padding: 40px;
  display: inline-block;
}
.inputEdit {
  width: 48%;
}
.selsty {
  width: 100%;
}
.selectsty {
  width: 48%;
}
.contentleft {
  float: left;
  width: 35%;
  height: 500px;
  overflow: auto;
}
.contentright {
  float: right;
  width: 55%;
}
.btnsty {
  width: 85px;
}
</style>
